package com.hw.one.collect.modbus.util;

import net.wimpi.modbus.net.SerialConnection;
import net.wimpi.modbus.net.TCPMasterConnection;
import net.wimpi.modbus.util.SerialParameters;

import java.net.InetAddress;

/***
 * @Author guoshenzhen
 */
public class ModbusConnection {

	/**
	 *
	 * @param ip
	 * @param port
	 * @return
	 * @throws Exception
	 */
	public static TCPMasterConnection openTcpConnection(String ip, int port) throws Exception {
		InetAddress addr = InetAddress.getByName(ip);
		// build the connection
		TCPMasterConnection con = new TCPMasterConnection(addr);
		con.setPort(port);
		con.connect();
		return con;
	}

	/**
	 *
	 * @param sParams
	 * @return
	 * @throws Exception
	 */
	public static SerialConnection openSerialConnection(SerialParams sParams) throws Exception {
		SerialParameters params = new SerialParameters();

		params.setPortName(sParams.portName);
		params.setBaudRate(sParams.baudRate);
		params.setDatabits(sParams.databits);
		params.setStopbits(sParams.stopbits);
		params.setParity(sParams.parity);
		params.setEncoding(sParams.encoding);
		
		// Open the Serial Connection
		SerialConnection con = new SerialConnection(params);
		con.open();
		return con;
	}

}
